// pages/customer/customer.js
const util = require('../../utils/util.js')
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    /*  */
    showNoDataIcon:false,
    userInfo_sj: {},
    /*  */
    activeIndex: '0',
    tabData: [
      {
        tabName: '保险客户'
      },
      {
        tabName: '非保险客户'
      }
    ],
    /*  */
    btnData: [
      {
        name: '添加客户'
      }
    ],
    /* 客户列表请求参数 */
    customerListArgs: {
      storeId: '',  //店铺id
      page: 1,
      pageSize: 10,
      type: '0',   //类别：0、系统分配客户，1、店铺客户
    },
    /* 页码 */
    customerPage: {
      '0': 1,
      '1': 1
    },
    /* 客户列表数据 */
    customerData: {
      '0': [],
      '1': []
    },
    /*  */
    showAddBtn: false,
    /*  */
    datalength:0
  },
  /* tab切换 */
  menuTabChange: function (e) {
    //console.log(e)
    if (this.data.customerListArgs.type === e.detail.activeIndex) return
    this.setData({
      'activeIndex': e.detail.activeIndex,
      'customerListArgs.type': e.detail.activeIndex
    })
    if (this.data.customerPage[e.detail.activeIndex + ''] === 1 && !this.data.customerData[e.detail.activeIndex + ''].length) {
      this.getClient()
    }
  },
  /* 获取客户列表 */
  getClient: function (isRefresh) {
    this.setData({
      showNoDataIcon: false
    })
    /* 下拉刷新 */
    if (isRefresh) {
      let pageNum = this.data.customerPage[this.data.activeIndex + '']
      let existData = this.data.customerData[this.data.activeIndex + '']
      pageNum = 1
      existData.splice(0, existData.length)
      this.setData({
        [`customerPage.${this.data.activeIndex}`]: pageNum,
        [`customerData.${this.data.activeIndex}`]: existData
      })
    }
    wx.showLoading({
      title: '获取客户',
      mask: true
    })
    return new Promise((resolve, reject) => {
      this.setData({
        'customerListArgs.type': this.data.activeIndex + '',
        'customerListArgs.page': this.data.customerPage[this.data.activeIndex]
      })
      wx.request({
        url: app.globalData.Url + '/wx/getClient',
        method: 'POST',
        header: this.data.userInfo_sj.header,
        data: util.json2Form(this.data.customerListArgs),   //
        success: res => {
          console.log(res)
          //token失效
          if(app.globalData.check_token(res.data.code))return new Promise((resolve,reject)=>{})
          if (res.data.code == '1' && Array.isArray(res.data.body.data)) {
            /* 无数据 */
            if (!res.data.body.data.length) {
              if(!this.data.customerData[this.data.activeIndex+''].length){
                this.setData({
                  showNoDataIcon: true
                })
              }
              return resolve()
            }
            let existData = this.data.customerData[this.data.activeIndex + '']
            res.data.body.data.forEach(item => {
              item.insuredMobile = item.insuredMobile ? item.insuredMobile : '-'
              existData.push(item)
            })
            //
            let pageNum = this.data.customerPage[this.data.activeIndex] * 1
            pageNum += 1
            this.setData({
              showAddBtn: true,
              ['customerPage.' + this.data.activeIndex]: pageNum
            })
            /*  */
            this.setData({
              [`customerData.${this.data.activeIndex}`]: existData
            })
            resolve()
          } else {
            wx.showToast({
              icon: 'none',
              title: '' + res.data.msg
            })
            if(!this.data.customerData[this.data.activeIndex+''].length){
              this.setData({
                showNoDataIcon: true
              })
            }
            reject()
          }
        },
        fail: err => {
          console.log(err)
          wx.showToast({
            icon: 'none',
            title: '获取数据失败'
          })
          if(!this.data.customerData[this.data.activeIndex+''].length){
            this.setData({
              showNoDataIcon: true
            })
          }
          reject()
        },
        complete: () => {
          wx.hideLoading()
        }
      })
    })
  },
  /* 获取客户详情 */
  getClientInfo: function (e) {
    console.log(e)
    let { info, index } = e.currentTarget.dataset
    app.globalData.setNeedAnimation.call(this, 'customerData.' + this.data.activeIndex, this.data.customerData[this.data.activeIndex], index).then(() => {
      //
      wx.navigateTo({
        url: '/pages/customer-detail/customer-detail',
        success: res => {
          if(this.data.activeIndex=='0'){
            res.eventChannel.emit('add-customer', {
              type: 'detail0',
              tabType: this.data.activeIndex,
              typeName:'保险客户',
              id: info.id
            })
          }
          if(this.data.activeIndex=='1'){
            res.eventChannel.emit('add-customer', {
              type: 'detail1',
              tabType: this.data.activeIndex,
              typeName:'非保险客户',
              id: info.id
            })
          }
        }
      })
    })
  },
  /* 添加客户 */
  insertStoreClient: function (e) {
    let { index } = e.currentTarget.dataset
    app.globalData.setNeedAnimation.call(this, 'btnData', this.data.btnData, index).then(() => {
      wx.navigateTo({
        url: '/pages/customer-detail/customer-detail',
        success: res => {
          res.eventChannel.emit('add-customer', {
            type: 'add',
            tabType: this.data.activeIndex,
            typeName:'非保险客户'
          })
        }
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    //
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //获取用户信息
    this.setData({
      userInfo_sj: app.globalData.get_userInfo()
    })
    this.setData({
      'customerListArgs.storeId': this.data.userInfo_sj.storeId
    })
    //
    this.getClient(true)
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  /*  */
  testTabTap: function (e) {
    console.log(e.detail)
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getClient(true).then(()=>{
      wx.stopPullDownRefresh({
        complete: (res) => {},
      })
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.getClient()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})